<template>
  <div>
    <!-- 入口文件 -->
    <VFormRender :form-json="formJson"
                 :form-data="formData"
                 :parent-api="parentApi"
                 :option-data="optionData"
                 ref="vFormRef"/>

    <!-- 成功或者失败 -->
    <report-result :info="reportResultInfo.info" :visible="reportResultInfo.visible"
                   @handle-cancel="closeReportResultLayer"/>
    <!-- 报到成功批量展示 弹窗-->
    <report-patient :info="reportPatientInfo.info"
                    :visible="reportPatientInfo.visible && layerNameKeySet.layerNameKeySuccess === 'report-patient'"
                    @handle-cancel="closeReportPatientLayer"/>
    <!-- 选择要报到的业务 -->
    <report-select-business :info="bizReportLayerInfo.info" :visible="bizReportLayerInfo.visible"
                            @handle-cancel="closeBizReportLayer" @handle-business="goToNext"/>
    <!-- 上饶市中医院 非预约时间报到确认弹窗名 弹窗-->
    <report-sure-power :info="reportSurePowerInfo.info" :visible="reportSurePowerInfo.visible"
                       @handle-cancel="closeReportSurePower" @handle-sure="reportSurePowerHandle"/>
    <!-- loading -->
    <popup-loading :info="popupLoadingInfo.info" :visible="popupLoadingInfo.visible"
                   @handle-cancel="closePopupLoading"/>

  </div>

</template>

<script>
import VFormRender from "@c/public/form-render/index.vue";
import {setRem2} from "@/utils/rem.js";
import {AndroidSDK} from "@/sdk/AndroidSdkService";
import {resetLongToStr} from "@/utils/biz/common/BizUtils";
import {SubjectUtil} from "@/utils/observer/SubjectUtil";
import {SetDateObserverBiz} from "@/utils/biz/common/SetDateObserverBiz";
import LayerComps from "@/components/public/layer/scenes";
import {UserCommitApi} from "@/api/user_common";
import {MachineObserverBiz} from "@/utils/biz/machine/MachineObserverBiz";
import {NumberMachineObserverBiz} from "@/utils/biz/number/NumberMachineObserverBiz";
export default {
  name: "MachineScreen",

  props: {
    formJson: {
      widgetList: [],
      formConfig: {
        devType: true
      },
    },
    formConfig: {},
    formData: Object,
    templateInfo: {},
    // 0表示门诊 1 第三方 2 其他
    apiType: {
      type: Number,
      default: 0
    },
    optionData: {},
  },

  components: {
    VFormRender,
    ...LayerComps
  },

  data() {
    return {
      parentApi: this.createParentOptions(),
      deviceInfo: null,
      // 组件缓存
      modelMap: {},
      // 消息
      eventBus: null,

      // 主事件交互逻辑 -- 可实现自己的，开始采用订阅，后来阉割了，降低复杂度
      mainEventBus:null,
      /**
       * 对内属性
       */
      commonJsonMap:{},
      // 结构
      commonJsonMapArr:{},
      // 是否允许一键报到
      isCanReportAll:true,
      // 当前报到患者数据缓存
      currentSignInfo:{},
      // 二级业务数据
      bizAttrList:[],
      currentBizInfo:null,
      currentInitParams:{},
      /**
       * 报到机 扫码数据缓存
       */
      reportScreenData: {
        printer: '',
        // 当前扫码数据缓存
        numData: {
          data: {
            unSignList: [],
            signList: []
          }
        },
      },

      signInfo:{
        // 是否开启患者隐私保护 0否 1是
        isNameProtect:'0',
        // 诊结数据查询 0否 1是
        isTreatEndPatient:'0'
      },
      // 报到机弹窗
      reportResultInfo: {visible: false, info: {state: 0,title: "",content: "",time: 60}},
      // 复诊医生弹窗
      reportDoctorInfo: {visible: false, info: {state: 0,title: "",content: "",time: 60}},
      // 报到成功弹窗
      reportPatientInfo: {visible: false, info: {state: 0,title: "",content: "",time: 60}},
      // 上饶市中医院 确认弹窗
      reportSurePowerInfo: {visible: false, info: {state: 0,title: "",content: "",time: 30}},
      // 业务报到弹窗
      bizReportLayerInfo: {
        visible: false,
        info: {
          state: 0,
          fontSize: 60,
          content: "请选择您要报到的业务",
          color:'#333333',
          time: 30,
          fontWeight:500,
          options:[]
        }
      },
      // 接口请求状态
      popupLoadingInfo: {visible: false, info: {content:'加载中...',color:'#f1e2e2'}},
      isOpenYiBao:false,
      yiBaoInfo:{
        orgId:'',
        url:''
      },
      patientNo:'',
      // 注册标识
      msgRegisterMark:'',
      // 弹窗配置
      layerNameKeySet:{
        // 正常报到成功弹窗
        layerNameKeySuccess:"report-patient",
        // 重复报到配置 -- 适合第一次查询没有可报到数据 同时有已报到的患者数据
        interceptSet:{
          open:false,
          title: '已报到',
          content: '请不要重复报到',
        }
      }

    };
  },

  mounted() {
    this.setRem();
    // 初始化
    this.init();
  },

  methods: {
    // 安卓报错信息的写入
    handleException(funcName, errType, errMsg) {
      AndroidSDK.writeLog(`${funcName}--${errType}-->${errMsg}`);
    },

    // 安卓正常写入日志
    handleWriteLog(funcName, msgContent) {
      AndroidSDK.writeLog(`${funcName}---->${msgContent}`);
    },

    /**
     * 安卓调用
     * @param obj
     */
    sdkServices(obj) {
      this.handleWriteLog("sdkServices", JSON.stringify(obj));
      try {
        if (obj.bizType && obj.bizType !== "") {
          switch (obj.bizType) {
            case "getDeviceInfoCallBack":
              this.deviceInfo = JSON.parse(resetLongToStr(obj.msgContent));
              this.initAfterGetDeviceInfo();
              break;
            case "webPing":
              AndroidSDK.androidPong();
              break;
            default:
              // 监听设置
              this.eventBus.$emit(obj.bizType, obj.msgContent);
          }
        } else {
          this.handleException("sdkServices", "数据错误", JSON.stringify(obj));
        }
      } catch (e) {
        this.handleException("sdkServices", "解析错误", JSON.stringify(obj));
      }
    },

    /**
     * 安卓调用
     * @param obj
     */
    sdkBizServices(obj) {
      this.handleWriteLog("sdkBizServices", JSON.stringify(obj));
      try {
        if (obj.bizType && obj.bizType !== "") {
          this.eventBus.$emit(obj.bizType, obj.msgContent);
        } else {
          this.handleException("sdkBizServices", "数据错误", JSON.stringify(obj));
        }
      } catch (e) {
        this.handleException("sdkBizServices", "解析错误", JSON.stringify(obj));
      }
    },

    /**
     * 初始化逻辑
     */
    init() {
      // 数据挂载
      parent.window.webSDKServices = this.sdkServices;
      parent.window.webSDKBizServices = this.sdkBizServices;
      AndroidSDK.androidPong();
      // 遍历数据 将模板数据存储到Map缓存中
      this.formJson.widgetList.forEach((item) => {
        this.modelMap[item.categoryType] = item;
      });
      // 设置接口中需要用的参数
      this.setParams();
      // 主题消息 Subject
      this.eventBus = new SubjectUtil();

      //获取终端信息
      AndroidSDK.getDeviceInfo();
    },
    /**
     * 初始化 模板参数
     */
    setParams() {
      // 加载主屏逻辑
      let mainInfo = this.modelMap["report"];
      if (mainInfo) {
        let configObj = mainInfo.options[mainInfo.options.config];
        // 请求Loading文案
        this.popupLoadingInfo.info.content = configObj.popupLoadingContent || '加载中...';
        // 特制消息标识
        this.msgRegisterMark = configObj.msgRegisterMark || '';

      }
    },
    /**
     * 获取设备信息后初始化
     */
    initAfterGetDeviceInfo() {
      // 特制消息清理+注册
      this.registerMsg();

      // 加载主屏逻辑
      let mainInfo = this.modelMap["report"];
      if (mainInfo) {
        let emp = new NumberMachineObserverBiz(this, this.deviceInfo, this.modelMap["report"]);
        this.eventBus.addObserver(emp);
        this.mainEventBus = emp;
        emp.init();
      }

      // 头部时间
      if (this.modelMap["header"]) {
        // 头部时间 - 观察者
        let emp = new SetDateObserverBiz(this, this.deviceInfo, this.modelMap["header"]);
        this.eventBus.addObserver(emp);
      }

    },

    /**
     * 消息注册
     */
    async registerMsg() {
      // 特制消息存在才会注册
      try {
        // 注册消息
        const {code, data} = await UserCommitApi.bindTerminalBusinessFlag({
          terminalId: this.deviceInfo.screenId,
          terminalType: this.deviceInfo.screenType,
          businessFlag: this.msgRegisterMark
        })
      } catch (e) {
        this.handleException('sdkBizServices', '特制消息注册失败 -- registerMsg -- >', JSON.stringify(e.stack));
      }
    },

    /**
     * 适配2k 4k
     */
    setRem() {
      const {resolution} = this.templateInfo;
      if (resolution) {
        // 重新计算尺寸
        setRem2(19.2, resolution.split("*")[0]);
        window.onresize = function () {
          setRem2(19.2, resolution.split("*")[0]);
        };
      }
    },

    /**
     * 全局弹窗关闭
     */
    closeReportResultLayer() {
      this.mainEventBus?.closeReportResultLayer();
    },
    /**
     * 关闭复诊医生弹窗
     */
    closeReportDoctorLayer() {
      this.mainEventBus?.closeReportDoctorLayer();
    },
    /**
     * 关闭报到成功
     */
    closeReportPatientLayer() {
      this.mainEventBus?.closeReportPatientLayer();
    },
    /**
     * 关闭业务报到
     */
    closeBizReportLayer() {
      this.mainEventBus?.closeBizReportLayer();
    },
    /**
     * 关闭业务报到
     */
    closePopupLoading() {
      this.mainEventBus?.closePopupLoading();
    },
    /**
     * 上饶市中医院 关闭 非预约提示 弹窗
     */
    closeReportSurePower() {
      this.mainEventBus?.closeReportSurePower();
    },
    /**
     * 开启安卓的读卡器
     */
    openReadCardScan() {
      AndroidSDK.reportSDKServices('readCardNoLimit');
    },
    /**
     * 关闭安卓的读卡器
     */
    cancelReadCardScan() {
      AndroidSDK.reportSDKServices('cancelNoLimitReadCard');
    },
    /**
     * 复诊报到
     * @param data
     */
    repeatReport(data){
      this.mainEventBus?.msgEvent({bizType:'repeatReport',data});
    },

    /**
     * 进入下级页面
     * @param item
     */
    goToNext(data){
      this.mainEventBus?.msgEvent({bizType:'goToNext',data});
    },

    /**
     * 上饶市中心医院 确认报到
     * @param item
     */
    reportSurePowerHandle(item){
      this.mainEventBus?.toReport(this.currentSignInfo);
    },

    createParentOptions() {
      return {
        self: this,
        executeParentMethod(key, data) {
          switch (key) {
            case "writeLog":
              // 内部组件调用 诙谐LOG 日志
              this.self.handleWriteLog('sdkBizServices','内部组件打印日志 -- >',data || '')
              break
            case "openReadCardScan":
              this.self.patientNo = "";
              // 开启安卓读卡
              this.self.openReadCardScan();
              break
            case "cancelReadCardScan":
              // 关闭安卓读卡
              this.self.cancelReadCardScan();
              break
            case "goToInit":
              // 取号机逻辑扫码
              this.self.mainEventBus?.msgEvent({bizType:'goToInitSignBiz',data});
              break
            case "handleHiddenSubmit":
              // 扫码查询 -- C端专用处理
              this.self.mainEventBus?.msgEvent({bizType:'handleHiddenSubmit',data});
              break
          }

        },
      };
    },

    /**
     * 获取多媒体
     * @param data
     */
    getVideoMedias(data) {
      try {
        let roomItem = this.modelMap["infoPublic"];
        const formRef = this.$refs.vFormRef;
        if (formRef) {
          this.$refs.vFormRef.executeChildMethod(roomItem?.id, "getVideoMedias", data || {});
        }
      } catch (e) {
        this.handleException("sdkBizServices", "内部组件异常 -- getVideoMedias -- >", JSON.stringify(e.stack));
      }
    }
  }

};
</script>
